const http = require('http')
const fs = require('fs')

http.createServer((request,response)=>{
    console.log('a request')
    // console.log(getPrototypChain(request))
    console.log('hi node')

    const {url,method,headers} = request
    if(url === '/' && method === 'GET'){
        fs.readFile('./index.html',(err,data)=>{
            if(err){
                response.writeHead(500,{
                    'Content-Type':'text/plain;charset=utf-8'
                })
                response.end('500 服务器挂了')
                return
            }
            response.statusCode = 200
            response.setHeader('Content-Type','text/html')
            response.end(data.toString())
        })
    } else if(url === '/users' && method === 'GET'){
        response.writeHead(200,{
            "Content-Type":'application/json'
        })
        response.end(JSON.stringify({
            a:'123'
        }))
    } else if(method==="GET" && headers.accept.indexOf('image.*' !== -1)){
        // 直接用readFile读取会把全部图片读取到服务器
        
        fs.createWriteStream("." + url).pipe(response)
    } else {
        response.statusCode = 400
        response.setHeader("Content-Type",'text/plain;charset=utf-8')
        response.end('404 没这玩意')
    }
})
.listen(3000,()=>{
    console.log('server at 3000')
})

function getPrototypChain(obj){
    const protoChain = []
    while(obj = Object.getPrototypeOf){
        protoChain.push(obj)
    }
    return protoChain
}